import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap(){
        this.elem = new int[10];
    }

    public void initElem(int[] array){
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];
            usedSize++;
        }
    }

    public void createHeap(){
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0 ; parent--) {
            shiftDown(parent,usedSize);
        }
    }

    //向下调整
    private void shiftDown(int parent,int len) {
        int child = parent*2 + 1;
        while(child < usedSize){
            if(child + 1 < usedSize && elem[child] < elem[child + 1]){
                child++;
            }
            if(elem[child] > elem[parent]){
                swap(elem,parent,child);
                parent = child;
                child = 2*child + 1;
            }else{
                break;
            }
        }
    }

    /**
     * 入队：仍然要保持是大根堆
     * @param val
     */
    public void push(int val) {
        if(isFull()){
            elem = Arrays.copyOf(elem,elem.length*2);
        }
        elem[usedSize] = val;
        shiftUp(usedSize);
        usedSize++;
    }

    private void shiftUp(int child) {
        int parent = (child - 1) / 2;
        while(parent > 0){
            if(elem[child] > elem[parent]){
                swap(elem,child,parent);
                child = parent;
                parent = (parent - 1) / 2;
            }else{
                break;
            }
        }
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public void pollHeap() {
        if(isEmpty()) return ;
        swap(elem,0,usedSize - 1);
        usedSize--;
        shiftDown((usedSize - 1) / 2,usedSize);
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    public boolean isFull(){
        return usedSize == elem.length;
    }

    //获取堆顶元素
    public int peekHeap() {
        if(isEmpty()) return -1;
        return elem[0];
    }

    private void swap(int[] array, int i, int j) {
        int tmp =array[i];
        array[i] =array[j];
        array[j] = tmp;
    }

    public void offer(int i) {
    }

    public void Del(int i) {
    }
}
